const STORAGE_KEY = "bearing-shop:device";

const generateFingerprint = () => {
  if (typeof crypto !== "undefined" && crypto.randomUUID) {
    return crypto.randomUUID();
  }
  const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
  return template.replace(/[xy]/g, c => {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

export const getDeviceFingerprint = () => {
  if (typeof window === "undefined") return generateFingerprint();
  const cache = window.localStorage.getItem(STORAGE_KEY);
  if (cache) {
    return cache;
  }
  const value = generateFingerprint();
  window.localStorage.setItem(STORAGE_KEY, value);
  return value;
};
